//
//  FCLPMenuLabel.m
//  AFNetworking
//
//  Created by WJC on 2020/7/4.
//

#import "FCLPMenuLabel.h"
@interface FCLPMenuLabel()
@property (nonatomic,strong) NSArray *menuAllArr;
@property (nonatomic,strong) UILongPressGestureRecognizer *longGesture;
@property (nonatomic,strong) returnMenuBlock block;
@end
@implementation FCLPMenuLabel

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}
-(instancetype)init{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}
 
/**
 * 让label可以响应用户操作
 */
- (void)setup
{
    self.userInteractionEnabled = YES;
}
 
 
//PS：下面两个方法必须在自定义Label里面实现
 
/**
 * 让label有资格成为第一响应者
 */
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
 
/**
 * label能执行哪些操作(比如copy, paste等等)
 * @return  YES:支持这种操作
*  由于这里需要实现自定义的中文菜单，而不是使用默认的，所以这里选择NO
 */
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
     return (action == @selector(menuCopyBtnPressed:));
}

-(void)setMenuItemWithMenuArr:(NSArray *)menuArr MenuBlock:(returnMenuBlock)returnBlock{
    self.userInteractionEnabled = YES;
   
    //在自定义cell中的init方法加入
    self.longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressCellHandle:)];

//    self.longGesture = longPressGesture;

    [self addGestureRecognizer:self.longGesture];
    self.menuAllArr = menuArr;
    self.block = returnBlock;
}
-(void)longPressCellHandle:(UILongPressGestureRecognizer *)gesture

{
 [self becomeFirstResponder];
UIMenuController *menuController = [UIMenuController sharedMenuController];
    [UIMenuController sharedMenuController].menuItems=nil;
    NSMutableArray *arr = [NSMutableArray new];
    if (self.menuAllArr.count<1) {
         UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(menuCopyBtnPressed:)];
        [arr addObject:copyItem];
    }else{
    for (int i = 0; i<self.menuAllArr.count; i++) {
       UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:self.menuAllArr[i] action:@selector(menuCopyBtnPressed:)];
      [arr addObject:copyItem];
    }
    }

    
 menuController.menuItems = arr;
[menuController setTargetRect:self.frame inView:self.superview];
[menuController setMenuVisible:YES animated:YES];


}


-(void)menuCopyBtnPressed:(UIMenuItem *)menuItem

{
    if (self.block) {
        self.block(menuItem.title);
        return;
    }
[UIPasteboard generalPasteboard].string = self.text;

}
@end
